package com.shilei.iterator.v3;

/**
 * @description: 构建一个容器 ，可以添加对象  数组
 * @author: 81271
 * @date: 2020-04-19 19:52
 */

class ArrayList_<E> implements Collection_<E>{
    private E[] objects = (E[]) new Object[10];
    //objects中下一个空位在哪， 或者说数组中存在着多少个元素
    private int index = 0;

    @Override
    public void add(E e) {
        if (index == objects.length) {
            E[] newObjects = (E[])new Object[objects.length * 2];
            System.arraycopy(objects, 0, newObjects, 0, objects.length);
            objects = newObjects;
        }
        objects[index] = e;
        index ++;
    }

    @Override
    public int size() {
        return index;
    }

    @Override
    public Iterator_<E> iterator() {
        return new ArrayListIterator<>();
    }

    private class ArrayListIterator<E> implements Iterator_<E>{
        int currIndex = 0;


        @Override
        public boolean hasNext() {
            return currIndex < index;
        }

        @Override
        public E next() {
            E e = (E)objects[currIndex];
            currIndex ++;
            return e;
        }
    }
}

